﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;
using System.ComponentModel;
using Common.ERROR_CODE;
namespace Common
{
    /* How to use
     *  MessageBox.Show(EnumUtils.stringValueOf(ErrorCode.ChocolateChip));
     */
    public class EnumUtils
    {
        public static int ProcessErrorCode(Enum ErrorCode, ref string MessageSystemError)
        {// ProcessErrorCode chi tra ve Success hoac SystemError
            if (ErrorCode.ToString() == ERROR_CODE_SIMPLE.SYSTEM_ERROR.ToString())
            {
                return (int)ERROR_CODE_SIMPLE.SYSTEM_ERROR;
            }
            if ((ErrorCode.ToString() != ERROR_CODE_SIMPLE.SUCCESS.ToString()) && (ErrorCode.ToString() != ERROR_CODE_SIMPLE.SYSTEM_ERROR.ToString()))
            {
                MessageSystemError = Common.EnumUtils.stringValueOf(ErrorCode);
                return (int)ERROR_CODE_SIMPLE.SYSTEM_ERROR;
            }
            return (int)ERROR_CODE_SIMPLE.SUCCESS;
        }

        /// <summary>
        ///Trả về Description từ Enum
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string stringValueOf(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            else
            {
                return value.ToString();
            }
        }

        /// <summary>
        /// Trả về Enum từ Description
        /// </summary>
        /// <param name="value"></param>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static object enumValueOf(string value, Type enumType)
        {
            string[] names = Enum.GetNames(enumType);
            foreach (string name in names)
            {
                if (stringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
                {
                    return Enum.Parse(enumType, name);
                }
            }

            throw new ArgumentException("The string is not a description or value of the specified enum.");
        }
    }
}
